import logging

from omni_bot_sdk1.utils.helpers import ensure_dir_exists
from omni_bot_sdk1.common.config import Config
from omni_bot_sdk1.utils.logging_setup import setup_logging
from omni_bot_sdk1.services.core.user_service import UserService
from omni_bot_sdk1.models import UserInfo
from omni_bot_sdk1.services.core.database_service import DatabaseService
from omni_bot_sdk1.rpa.image_processor import ImageProcessor
from omni_bot_sdk1.rpa.ocr_processor import OCRProcessor
from omni_bot_sdk1.rpa.window_manager import WindowManager

from omni_bot_sdk1.rpa.controller import RPAController



class Bot:
    """
    Omni-Bot的核心平台运行时环境。
    负责生命周期管理、组件初始化、插件上下文注入等。
    不直接处理业务逻辑，而是为插件和服务提供统一的运行支撑。
    """

    STATUS_STARTING = "starting"  # 启动中
    STATUS_RUNNING = "running"  # 运行中
    STATUS_PAUSED = "paused"  # 已暂停
    STATUS_STOPPING = "stopping"  # 停止中
    STATUS_STOPPED = "stopped"  # 已停止
    STATUS_FAILED = "failed"  # 启动/运行失败


    def __init__(self, config_path : str = "config.yaml"):
        """
        初始化Bot对象，进完成依赖注入和对象组装，不执行耗时任务
        """
        # 在项目根目录上创建一个存储运行时图片的数据目录
        ensure_dir_exists("runtime_images")
        self.config: Config = Config(config_path)
        setup_logging(
            log_dir=self.config.get("logging.path", "logs"),
            log_level=self.config.get("logging.level", logging.INFO),
        )
        self.logger = logging.getLogger(self.__class__.__name__)
        self.logger.warning("图片AES key需要在微信启动后一小段时间内才能获取，如果无法获取请重新启动微信后重试")

        self.is_running = False
        self.is_paused = False  # 标记是否处于暂停状态
        self._status = None  # 当前状态
        self._status_callbacks = []  # 状态变更回调函数列表

        # 用户服务与用户信息的初始化
        self.user_service: UserService = UserService(self.config.get("dbkey"))
        self.user_info: UserInfo = self.user_service.user_info()
        allow_versions = ["4.0.6.33", "4.0.6.13"]
        if self.user_info.version not in allow_versions:
            self.logger.error(
                f"当前微信版本不在支持范围内,目前支持的版本包括：{','.join(allow_versions)}"
            )
            self.logger.info("您可以前往：https://github.com/cscnk52/wechat-windows-versions/releases 下载历史版本微信")
            exit(1)

        #todo 这一块是什么意思？链接什么数据库？sqllite？连接的句柄文件也没有吗？释放句柄文件也没有吗？
        # 数据库服务初始化（需最先初始化）
        self.db: DatabaseService = DatabaseService(self.user_service)

        # RPA相关组件初始化
        self.image_processor: ImageProcessor = self._create_image_processor()
        self.ocr_processor: OCRProcessor = self._create_ocr_processor()
        self.window_manager: WindowManager = self._create_window_manager()
        self.rpa_controller: RPAController = self._create_rpa_controller()

    def _create_image_processor(self) -> ImageProcessor:
        """
        创建ImageProcessor实例。
        """
        return ImageProcessor()

    def _create_ocr_processor(self) -> OCRProcessor:
        """
        创建OCRProcessor实例，并注入OCR相关配置。
        """
        ocr_config = self.config.get("rpa.ocr", {})
        self.logger.info(f"OCRProcessor configured with: {ocr_config}")
        return OCRProcessor(ocr_config=ocr_config)

    def _create_window_manager(self) -> WindowManager:
        """
        创建WindowManager实例，并注入依赖和RPA配置。
        """
        rpa_config = self.config.get("rpa", {})
        return WindowManager(
            image_processor=self.image_processor,
            ocr_processor=self.ocr_processor,
            rpa_config=rpa_config,
        )
